import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { UserService } from "../../user/service/user.service";


@Injectable()
export class AuthService {
    constructor(
        private userService: UserService,
        private jwtService: JwtService
    ) { }

    async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.userService.findOne(username);
        if (user && user.password === pass) {
            const { password, ...result } = user;
            return result;
        }
        return null;
    }

    async login(user: any): Promise<any> {
        const userEntity = await this.userService.findOne(user.username);
        const payload = { username: userEntity.username, userId: userEntity.id, roles: userEntity.roles };
        if (userEntity)
            return {
                access_token: this.jwtService.sign(payload),
            };
    }

}